<?php
namespace Home\Controller;
use Think\Controller;
use Qiniu\Auth;
use OSS\Core\OssException;
use OSS\OssClient;
use Think\Cache\Driver\Redis;
use Lib\Alidayu\SendSMS;
header("Access-Control-Allow-Origin: *");
class CommonController extends Controller
{

		public function Is_login()
		{
				$c = strtolower(CONTROLLER_NAME);              //当前需要调用controller
				$a = strtolower(ACTION_NAME);                  //当前需要调用的action
				$no_check_c = C('NO_CHECK_LOGIN_CONTROLLER');  //不需要检测的controller
				$no_check_a = C('NO_CHECK_LOGIN_ACTION');      //不需要检测的action
				//当前调用的控制器是否不需要检测
				if(in_array($c, $no_check_c)){
						return true;
				}
				//当前action是否不需要检测
				if(in_array($a, $no_check_a)){
						return true;
				}
				//当前controller下面的action是否不需要检测
				if(in_array($c."/".$a, $no_check_a)){
						return true;
				}
				// $memberData = RedisGet('heardadminData');
				if(empty(cookie('heardadminData'))){
						$this->error('请重新登录',"/Home/Login",1);
						// echo '<script>alert("系统检测用户未登录或登录超时,请重新登录");setTimeout(window.location.href=\'/home/Login\',300);</script>;';
				}
		}
		public function Is_power($power="null")
		{
			$this->assign('founder',cookie('founder'));
				$user = explode(",", cookie('heardadminPower'));
				if(in_array($power, $user)||cookie('founder')==1){
						return true;
				}else{
					cookie('heardadminData',null);
					cookie('heardadminPower',null);
					cookie('founder',null);
					$this->error('当前账号没有权限，请重新登录',"/Home/Login",1);
				}
		}
		/**
		 * 接口成功返回格式
		 * @param $message //提示信息
		 * @param $data //数据
		 * @return string 处理好的json数据
		 */
		public function ApiSuccess($message,$data='')
		{
				$result['code'] = '000000';
				$result['message'] = $message;
				if($data){
						$result['data'] = $data;
				}
				return $this->ajaxReturn($result);
		}

		/**
		 * 接口失败返回格式
		 * @param $message //提示信息
		 * @param $code //错误码
		 * @return string 处理好的json数据
		 */
		public function ApiError($message,$code)
		{
				$result['code'] = $code;
				$result['message'] = $message;
				return $this->ajaxReturn($result);
		}


		// 验证字段是否为空
		public function _isEmpty($data,$message)
		{
				if($data == NULL || empty($data) || $data == FALSE){
						$this->ApiError($message.'不能为空','999999');
				}
		}

		//判断用户是否可以进入页面
		public function _status($data,$status)
		{
				if (empty($data)){
						$this->redirect('/');
				}
				$res = M('member')->where(array('username'=>$data))->find();
				if ($res == NULL || $res['status'] != $status) {
						$this->redirect('/');
				}
		}

		// 判断上传文件是否为空
		public function isExpertiseMusic_essential($data,$message)
		{
				if(empty($_FILES[$data]['tmp_name'])){
						E($message.'没有文件上传');
				}else{
						return true;
				}
		}

		public function isExpertise($data)
		{
				if(empty($_FILES[$data]['tmp_name'])){
						return false;
				}else{
						return true;
				}
		}


		// 判处理用户自定义时间
		public function getTime($h,$m)
		{
				$time = (int)$h * 60 + (int)$m;
				return $time;
		}

		// 七牛上传方法
		public function _postQiniu($type,$file)
		{
				$config = $type == 1 ?  C('CONFIG_MUSIC') : C('CONFIG_IMG');
				$config_qiniu=C('CONFIG_QINIU');
				$Upload = new \Think\Upload($config,'Qiniu',$config_qiniu);
				$info = $Upload->uploadOne($_FILES[$file]);
				if($info == false){
						E('上传音频文件失败');
				}else{
						return $info['url'];
				}
		}


		public function uploadFace() {
				//if (!$this->isPost()) {
				//  $this->error('页面不存在');
				//}
				//echo 'asdfsaf';die;
				$upload = $this->_upload('mediapic');
				$this->ajaxReturn($upload);
		}

		Private function _upload ($path) {
				import('ORG.Net.UploadFile');   //引入ThinkPHP文件上传类
				$obj = new \Think\Upload(); //实例化上传类
				$obj->maxSize = 2000000;    //图片最大上传大小
				$obj->savePath =  $path . '/';  //图片保存路径
				$obj->saveRule = 'uniqid';  //保存文件名
				$obj->uploadReplace = true; //覆盖同名文件
				$obj->allowExts = array('jpg','jpeg','png','gif');  //允许上传文件的后缀名
				$obj->autoSub = true;   //使用子目录保存文件
				$obj->subType = 'date'; //使用日期为子目录名称
				$obj->dateFormat = 'Y_m';   //使用 年_月 形式
				//$obj->upload();die;
				$info   =   $obj->upload();
				if (!$info) {
						return array('status' => 0, 'msg' => $obj->getError());
				} else {
						foreach($info as $file){
								$pic = $file['savepath'].$file['savename'];
						}
						//$pic =  $info[0][savename];
						//echo $pic;die;
						return array(
										'status' =>1,
										'path' => $pic
						);
				}
		}

	public function php_upload(){
		$file = $_FILES['photo'];//得到传输的数据
		$name = $file['name'];
		if(!empty($name)){
		//得到文件名称

		$type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型,并且都转化成小写
		$allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型
		//判断文件类型是否被允许上传
		if(!in_array($type, $allow_type)){
			//如果不被允许,则直接停止程序运行
			return ;
		}
		//判断是否是通过HTTP POST上传的
		if(!is_uploaded_file($file['tmp_name'])){
			//如果不是通过HTTP POST上传的
			return ;
		}
		$path =dirname(dirname(dirname(__DIR__)))."/Uploads/mediapic/".date('Y-m-d',time())."/";
		if(!file_exists(path)){
				mkdir($path,0777,true);
		}

		$upload_path = $path; //上传文件的存放路径
		$p=  pathinfo($_FILES['photo']['name']);
		$f_name=time().mt_rand(100, 999).'.'.$p['extension'];

		//开始移动文件到相应的文件夹
		if(move_uploaded_file($file['tmp_name'],$upload_path.$f_name)){
			$d = "/Uploads/mediapic/".date('Y-m-d',time())."/".$f_name;
		}else{
			$d = '';
		}
		return $d;
	}
}
	public function uptoken(){
		header("Access-Control-Allow-Origin: *");
		Vendor('Qiniu.autoload');

		// 需要填写你的 Access Key 和 Secret Key
		$accessKey = 'bQ8w3DATzMSkFNJ_lypBz5JOgWjf5zanFiQdOwtW';
		$secretKey = 'uSSIa9XGavTeWGcAWcVi7fb6B-N-ykkbiUat9Anb';

		// 构建鉴权对象
		$auth = new Auth($accessKey, $secretKey);

		// 要上传的空间
		$bucket = 'audio';//audio

		$name = time().rand(10000,99999);

		$key = \Qiniu\base64_urlSafeEncode('audio:'.$name.'.m3u8');

		//上传策略
		$policy = [
				'persistentPipeline'  =>       'a00001',
				"deadline"            =>       time()+3600,
				"persistentOps"       =>       "avthumb/m3u8/segtime/10/ab/64k/ar/44100/acodec/libfaac|saveas/".$key,
				"persistentNotifyUrl" =>       "http://".ADMIN_URL."Home/Common/GetNotify",
		];

		// 生成上传 Token
		$token = $auth->uploadToken($bucket,null,3600,$policy);
		$res = array('uptoken'=>$token);
		exit(json_encode($res));
}
public function uptoken_media(){
	header("Access-Control-Allow-Origin: *");
	Vendor('Qiniu.autoload');

	// 需要填写你的 Access Key 和 Secret Key
	$accessKey = 'bQ8w3DATzMSkFNJ_lypBz5JOgWjf5zanFiQdOwtW';
	$secretKey = 'uSSIa9XGavTeWGcAWcVi7fb6B-N-ykkbiUat9Anb';

	// 构建鉴权对象
	$auth = new Auth($accessKey, $secretKey);

	// 要上传的空间
	$bucket = 'media';

	// 生成上传 Token
	$token = $auth->uploadToken($bucket);
	$res = array('uptoken'=>$token);
	exit(json_encode($res));
}
public function uptoken_image(){
	header("Access-Control-Allow-Origin: *");
	Vendor('Qiniu.autoload');

	// 需要填写你的 Access Key 和 Secret Key
	$accessKey = 'bQ8w3DATzMSkFNJ_lypBz5JOgWjf5zanFiQdOwtW';
	$secretKey = 'uSSIa9XGavTeWGcAWcVi7fb6B-N-ykkbiUat9Anb';

	// 构建鉴权对象
	$auth = new Auth($accessKey, $secretKey);

	// 要上传的空间
	$bucket = 'image';

	// 生成上传 Token
	$token = $auth->uploadToken($bucket);
	$res = array('uptoken'=>$token);
	exit(json_encode($res));
}
	// 七牛异步回调
		public function GetNotify()
		{
				/* TODO: 接受流信息 */
				$body = file_get_contents('php://input');

				/* TODO: json_decode编码 */
				$body = json_decode($body,true);

				/* TODO: 获取所需参数 */
				$key = $body['items'][0]['key'];
				$inputkey = $body['inputKey'];

				/* TODO: 验证信息修改对应数据 */
				if (!empty($key)&&!empty($inputkey)) {
					$data['key'] = QN_AUDIO_URL.$key;
					$data['inputkey'] = QN_AUDIO_URL.$inputkey;
					M('qnvoiceurl')->add($data);
				}

		}

	public  function PostOss($article){
		vendor('aliyun.autoload');
		$accessKeyId = "LTAIIpe6DwZznQ3t";//去阿里云后台获取秘钥
		$accessKeySecret = "hHycAKcsPcnHRKBqMaEQwnvC5Qkosa";//去阿里云后台获取秘钥
		$endpoint = "oss-cn-beijing.aliyuncs.com";//你的阿里云OSS地址
		$bucket= "heard";
		$object = md5(time().rand(1000,9999));
		try {
				$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
				$ossClient->putObject($bucket, $object, $article);
		} catch (OssException $e) {
				// return false;
				print $e->getMessage();
		}
		return $object;
	}
	public function GetOss($object="203ba26712b2ab2fb374001614898390"){
		vendor('aliyun.autoload');
		$accessKeyId = "LTAIIpe6DwZznQ3t";
		$accessKeySecret = "hHycAKcsPcnHRKBqMaEQwnvC5Qkosa";
		$endpoint = "oss-cn-beijing.aliyuncs.com";
		$bucket= "heard";
		$object = $object;
		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$content = $ossClient->getObject($bucket, $object);
			//	print("object content: " . $content);
			// echo $content;
			return $content;
		} catch (OssException $e) {
			return false;
			//	print $e->getMessage();
		}
	}
function adminlog($message,$type=0){
	M('adminlog')->add(array("adminid"=>urlsafe_b64decode(cookie('heardadminData')),"time"=>date("Y-m-d H:i:s",time()),"message"=>$message,"type"=>$type));
}
/*------------------------------------------------------------------------------------------*/
/**
* 抢单时间截至分配订单
* @param $oid 		订单id
* @param $switch 	用户开关  0关闭  1开启
*/
function allocation_order($order)
{
	// p($order);exit();
	$oid = $order['id'];
	$db_order = M('order');
	$vo['status'] = 3;
	$result = $db_order->where(array('id'=>$oid))->save($vo);
	if ($order['sub_type'] == 1) {
		$orderGetmember = "100001";
	}
	$start2 = microtime(true);
	$userdata = $this->GroupOrder($oid,$orderGetmember);
	$end2 = microtime(true);echo "redis=".round($end2-$start2,3)."|";
	$orderGetmember = $userdata['win_uuid'];
	$hands_map = $userdata['hands_map'];

	if(empty($orderGetmember)){
		$userdata = $this->GroupOrder($oid);
		$orderGetmember = $userdata['win_uuid'];
		$hands_map = $userdata['hands_map'];
		echo $oid."userdata is empty.";
	}
	// 修改订单状态
	$o['user_id'] = $orderGetmember;
	$o['operating_time'] = time();
	$result1 = $db_order->where(array('id'=>$oid,'status'=>3))->save($o);
	if($result1 == true){
		if ($orderGetmember != "100001") {
			M('sendmember')->where(array('uuid'=>$orderGetmember))->save(array('getorder'=>1));
			// 插入订单收入表
			$income['time'] = time();
			$income['type'] = 0;
			$income['uuid'] = $orderGetmember;
			$income['amount'] = $order['price'];
			if($order['requirement']==3) {
				$income['amount'] = $order['price']+$order['increase_price'];
			}
			if ($order['bgm_id'] != 0) {
				$income['amount'] = $income['amount']+10;
			}
			$income['oid'] = $oid;
			M('income')->add($income);
		}
		// 发送socket通知
		// $this->postsocket($oid);
		$socket = new \Home\Controller\SocketController();
		$message2['type'] = 'order';
		$message2['data']['oid'] = $oid;
		$message2['data']['uuid'] = $orderGetmember;
		$message2['data']['bgm_id'] = $order['bgm_id'];
		if ($order['bgm_id']!=0) {
			$bgm_url = M('bgm')->where(array('id'=>$order['bgm_id']))->getField('audio');
			$message2['data']['bgm_url'] = "LINUXURL.'Get/download?url='".$bgm_url;
		}
		$message2['data']['hands_map'] = json_encode($hands_map,TRUE);
		$socket->send_to_group($oid,$message2);
			// 发送微信模板消息通知
		$this->PostMessage($oid);
	}else{
		echo "-|订单分配失败:".$oid;
	}

}
	// 分组排序修改状态 返回得分最高的主播uuid
	public function GroupOrder($oid,$win_uuid=0){
		$hands_map = array();
		$score = 0;
		$Redis = RedisNew();
		# 挨个瞅瞅pk一下 看看抢到了没
		$order_lists = json_decode($Redis->get('order'.$oid),TRUE);
		$order_lists['status'] = 1;
		$Redis->set('order'.$oid,json_encode($order_lists));
		$order_list = $order_lists['list'];
		// p($order_list);exit();
		$member_list = M('member')->where(array('status'=>9))->field('uuid,level,score')->select();
		$unread = json_decode($Redis->get("unread"),TRUE);
		$socket = new \Home\Controller\SocketController();
		foreach ($order_list as $key => $vo) {
			# 只处理参与抢单的
			if ($vo == 1) {
				# 取出用户的订单列表 找出对应的订单 倒叙查找
				$uuid_lists = json_decode($Redis->get('uuid'.$key),TRUE);
				$uuid_list = array_reverse($uuid_lists['order_list']);

				# 修改对应订单的用户状态
				foreach ($uuid_list as &$value) {
					# 根据用户当前状态来更改state 先不管谁抢到了 假设谁都没抢到
					if ($value['oid'] == $oid) {
						if ($value['state'] == 3) {
							$value['state'] = 7;
							array_push($hands_map, $key);
						}
						/*if ($value['state'] == 1) {
							$value['state'] = 11;
						}*/
					}
				}
				# 存回去
				$uuid_lists['order_list'] = array_reverse($uuid_list);
				$Redis->set('uuid'.$key,json_encode($uuid_lists));
				// $variable[$key] = $uuid_lists;

				# 找出最高分主播
				if ($win_uuid != "100001") {
					if ($order_list[$key] == 1) {
						$member = [];
						foreach ($member_list as $k => $member) {
							if ($member['uuid'] == $key) {
								$member['score'] = $member['score'] < 0 ? 0 : $member['score'];
								$member['score'] = $member['score'] > 60 ? 60 : $member['score'];
								$member_score = $member['score'] + $member['level'];
								if ($member_score > $score) {
									$score = $member_score;
									# 取出当前最高分主播
									$win_uuid = $key;
								}
							}
						}
					}
				}
			}
			if ($vo == 3 && $unread[$key]['1']>0) {
				$unread[$key]['1'] -= 1;
			}
			# 给所有已读的用户发送超时消息
			if ($vo == 2) {
				$data['type'] = 'timeout';
				$data['id'] = $oid;
				$socket->send_to_uid($key,$data);
			}
		}
		$Redis->set('unread',json_encode($unread));
		// $this->pipeline($variable);
		// echo $win_uuid;
		// $this->where(array('id'=>$oid))->save(array('uuid'=>$win_uuid));
		# 找到了抢到了单的主播 我们改变当前主播的状态
		$uuid_lists = json_decode($Redis->get('uuid'.$win_uuid),TRUE);
		$uuid_list = array_reverse($uuid_lists['order_list']);
		foreach ($uuid_list as &$value) {
			if ($value['oid'] == $oid) {
				$value['state'] = 5;
			}
		}
		# 把抢到了单的存回去
		$uuid_lists['order_list'] = array_reverse($uuid_list);
		$Redis->set('uuid'.$win_uuid,json_encode($uuid_lists));
		# 为所有在线的人广播 抢单成功失败的消息超时的消息
		// $this->order_broadcast($win_uuid);
		$data['win_uuid'] = $win_uuid;
		$data['hands_map'] = $hands_map;
		return $data;
	}
		/*public function GroupOrder($oid)
		{
				// M()->execute("unlock tables");
						// ->lock(true)
				$data =  M('theorderinfo i')
						->join('__MEMBER__ m ON i.uuid = m.uuid')
						->join('__THEORDER__ t ON i.oid = t.id')
						->where(array('i.oid'=>$oid,'i.status'=>1))
						->field('m.uuid,m.level,m.score,i.operatingtime,t.demand')
						->group('m.uuid')
						->select();
				// M()->execute("unlock tables");
				// 数组重构 排序 大于60分按60分判断
				$list = [];
				foreach ($data as &$vo) {
						$vo['score'] = $vo['score'] > '60' ? '60' : $vo['score'];
						if ($vo['demand'] == 2) {
							$vo['px'] = $vo['level'];
						}else{
							$vo['px'] = $vo['level'] + $vo['score'];
						}
						$list[$vo['px']] = $vo;
				}
				krsort($list);
				$list = array_values($list);
				if ($list[0]['uuid']) {
					return $list[0]['uuid'];
				}else{
					return $this->GroupOrder($oid);
				}
		}*/
/**
* 获取订单信息准备重新发单
* @param $oid 		订单id
* @param $fail 		重新发单状态
* @param $switch 	用户开关  0关闭  1开启
*/
public function getthetimeoutorder($order,$signsystem){
	// 如果预约单超时未完成 变成普通单重新发单
	if($order['requirement'] == 2) {
		$wordnumber = $order['words']<100?100:$order['words'];
		$order['deliver_time'] = round($wordnumber/100)*$signsystem['9']['value']+$signsystem['10']['value'];
		$order['price'] = $order['price']+$order['increase_price'];
		$order['increase_price'] = 0;
		$order['requirement'] = 1;
	}
	$now_time = time();
	// 29个
	$data['media_id'] = $order['media_id'];
	$data['media_name'] = $order['media_name'];
	$data['media_tel'] = $order['media_tel'];
	$data['media_pic'] = $order['media_pic'];
	$data['media_message'] = $order['media_message'];
	$data['article_id'] = $order['article_id'];
	$data['bgm_id'] = $order['bgm_id'];
	$data['type'] = $order['type'];
	$data['requirement'] = $order['requirement'];
	$data['title'] = $order['title'];
	$data['content'] = $order['content'];
	$data['words'] = $order['words'];
	$data['category'] = $order['category'];
	$data['speed'] = $order['speed'];
	$data['sex'] = $order['sex'];
	$data['level'] = $order['level'];
	$data['is_read_title'] = $order['is_read_title'];
	$data['price'] = $order['price'];
	$data['increase_price'] = $order['increase_price'];
	$data['max_join_num'] = $order['max_join_num'];
	$data['deliver_time'] = $order['deliver_time'];
	$data['add_time'] = date("YmdH",$now_time);
	$data['createtime'] = $now_time;
	$data['snatch_time'] = $order['snatch_time'];
	$data['state'] = 1;
	$data['email'] = $order['email'];
	$data['pay_type'] = $order['pay_type'];
	$data['pay_status'] = 1;
	$data['pay_time'] = $now_time;
	// p($data);exit();
	$result = M("order")->add($data);
	$data['id'] = $result;
	// $orderdata = M("order")->where(array("id"=>$result))->find();
	$leveldata = M("systemsetup")->where(array("type"=>1))->order('value desc')->select();
	$this->order_push($data,$signsystem,$leveldata);
	return $result;
}

/**
* 获取订单信息准备重新发单(签约单第一次流转开关打开的认证主播第二次流转关闭开关的认证主播第三次流转为加急打开开关的主播第四次流转关闭开关的主播，签约单时间按时间点计算)
* @param $oid 		订单id
* @param $fail 		重新发单状态
* @param $switch 	用户开关  0关闭  1开启
*/
public function gettheorder($order,$signsystem){
	$now_time = time();
	// 30个
	$data['media_id'] = $order['media_id'];
	$data['media_name'] = $order['media_name'];
	$data['media_tel'] = $order['media_tel'];
	$data['media_pic'] = $order['media_pic'];
	$data['media_message'] = $order['media_message'];
	$data['article_id'] = $order['article_id'];
	$data['bgm_id'] = $order['bgm_id'];
	$data['type'] = $order['type'];
	$data['sub_type'] = $order['sub_type'];
	$data['requirement'] = $order['requirement'];
	$data['title'] = $order['title'];
	$data['content'] = $order['content'];
	$data['words'] = $order['words'];
	$data['category'] = $order['category'];
	$data['speed'] = $order['speed'];
	$data['sex'] = $order['sex'];
	$data['level'] = $order['level'];
	$data['is_read_title'] = $order['is_read_title'];
	$data['price'] = $order['price'];
	$data['increase_price'] = $order['increase_price'];
	$data['max_join_num'] = $order['max_join_num'];
	$data['deliver_time'] = $order['deliver_time'];
	$data['add_time'] = date("YmdH",$now_time);
	$data['createtime'] = $now_time;
	$data['snatch_time'] = $signsystem['3']['value'];
	$data['state'] = 1;
	$data['email'] = $order['email'];
	$data['pay_type'] = $order['pay_type'];
	$data['pay_status'] = 1;
	$data['pay_time'] = $now_time;

	// p($data);exit();
	$result = M("order")->add($data);
	// $orderdata = M("order")->where(array("id"=>$result))->find();
	$leveldata = M("systemsetup")->where(array("type"=>1))->order('value desc')->select();
	if ($result) {
		$data['id'] = $result;
		$this->order_push($data,$signsystem,$leveldata);
	}
	return $result;
}
/**
* 给主播发送通知
* @param $orderdata 		订单信息
* @param $signsystem 		系统信息
* @param $switch 	用户开关  0关闭  1开启
* @param $leveldata 		等级信息
*/
public function order_push($orderdata,$signsystem,$leveldata){

	echo "(".date("i:s",time());

	$oid = $orderdata['id'];
	$type = $orderdata['type'];
	$level_user = $this->select_member($orderdata,$signsystem,$leveldata);
	// p($level_user);
	// exit();
	$Redis = RedisNew();
	foreach ($level_user as $key => $value) {
		$order_array['list'][$value['uuid']] = 3;
		$order_array['status'] = 0;
	}
	$Redis->set('order'.$oid,json_encode($order_array));
	// p($level_user);exit();
	foreach ($level_user as $key => $value) {
		$uuid_array = json_decode($Redis->get("uuid".$value['uuid']),TRUE);
		$arr['oid'] = $oid;
		$arr['shot_time'] = 1;
		$arr['state'] = 1;
		$arr['type'] = $type;
		$uuid_array['order_list'][] = $arr;
		$Redis->set('uuid'.$value['uuid'],json_encode($uuid_array));
		if ($value['openid']) {
			$wedata[$key]['openid'] = $value['openid'];
			$wedata[$key]['oid'] = $oid;
			$wedata[$key]['token'] = $value['token'];
			$wedata[$key]['uuid'] = $value['uuid'];
		}
	}
	$unread = json_decode($Redis->get("unread"),TRUE);
	foreach ($level_user as $key => $value) {
		if (empty($unread[$value[uuid]]['1'])) {
			$unread[$value[uuid]]['1'] = 0;
		}
		if (empty($unread[$value[uuid]]['2'])) {
			$unread[$value[uuid]]['2'] = 0;
		}
		switch ($type) {
			case '1':$unread[$value[uuid]]['1'] += 1;break;
			case '2':$unread[$value[uuid]]['2'] += 1;break;
		}
	}
	$Redis->set('unread',json_encode($unread));
	// $this->pipeline($variable);
	// p($order_array);
	$snatch_time = M("systemsetup")->where("id=4")->where(array("type"=>0))->find()['value'];
	echo "-".date("i:s",time());
	// $GetSingAccessToken = $this->GetSingAccessToken();
	$GetAccessToken = $this->GetAccessToken();
	$template = A("Template");
	foreach ($wedata as $key => $user) {
		$pusharray[] = $template->sendorderMessage($user,$orderdata,$snatch_time,$GetAccessToken);
	}
	// p($pusharray);
	echo "-".date("i:s",time()).")";
	// exit();
	$res = curl_multi($pusharray);
	// p($res);
	return $res;
}
public function select_member($orderdata,$signsystem,$leveldata){
	$db_memberpool = M("memberpool");
	$sub_type = $orderdata['sub_type'];
	$level = $orderdata['level'];
	$category = $orderdata['category'];
	$ordersex = $orderdata['sex'];
	$requirement = $orderdata['requirement']==2?1:0;
	$pool_switch = $signsystem['21']['value']+0;
	// 新人单
	if ($pool_switch==0 || ($sub_type==2 || $sub_type==3)) {
		$where = " 1=1 ";
		$where .= " and (soundtype like '%".($category-1)."%')";
		if ($ordersex != 0) {
			$where .= " and sex = $ordersex";
		}
		// 新人单
		if ($sub_type == 2) {
			$where .= " and ordertype=0";
		}
		// 加急单
		if ($requirement == 2) {
			$where .= " and (score>52)";
		}
		foreach ($leveldata as $key => $value) {
			if ($level == $value['id']) {
				$where .= " and m.uuid != 100001 and status = 9 and level >=$value[value] ";
				$level_user = M("member m")->join('__WECHAT__ w ON m.uuid = w.uuid',LEFT)->field('m.uuid,w.openid,w.token')->where($where)->select();
			}
		}
	}else{
		$limit = 3;
		$label = $category.$ordersex.$level.$requirement;
		$where = "label = $label";
		switch ($level) {
			case '7':
				$where .= " or label = ".($label-10);
				$where .= " or label = ".($label-20);
				break;
			case '6':
				$where .= " or label = ".($label-10);
				break;
		}
		$level_user = $db_memberpool->where($where)->where(array("type"=>0))->order('rand()')->limit($limit)->select();
		if (count($level_user)<$limit && $db_memberpool->where($where)->count()>=$limit) {
			$db_memberpool->where($where)->save(array("type"=>0));
			return $this->select_member($orderdata,$signsystem,$leveldata);
		}
		foreach ($level_user as $key => $value) {
			$db_memberpool->where($where)->where(array("uuid"=>$value['uuid'],"type"=>0))->save(array("type"=>1));
		}
	}
	return $level_user;
}


/**
* 抢单成功时给主播发送通知
* @param $oid 		订单id
*/
// 处理用户操作订单信息
protected function PostMessage($oid)
{
	$memberlist = array();
	$order_lists = json_decode(RedisGet('order'.$oid),TRUE);
	$order_list = $order_lists['list'];
	// p($order_list);exit();
	foreach ($order_list as $key => $vo) {
		if ($vo == 1) {
			$uuid_lists = json_decode(RedisGet('uuid'.$key),TRUE);
			$uuid_list = array_reverse($uuid_lists['order_list']);
			foreach ($uuid_list as &$value) {
				if ($value['oid'] == $oid) {
					if ($value['state'] == 5) {
						$userdata = M("wechat")->where(array("uuid"=>$key))->find();
						$userdata['state'] = 5;
						$memberlist[] = $userdata;
					}
					if ($value['state'] == 7) {
						$userdata = M("wechat")->where(array("uuid"=>$key))->find();
						$userdata['state'] = 7;
						$memberlist[] = $userdata;
					}
				}
			}
		}
	}
	// p($memberlist);exit();
	$order = M('order')->where(array("id"=>$oid))->find();
	A("Template")->template_order_api($order,$memberlist);
}
/**
* 抢单成功时给主播发送通知
* @param $uuid 		用户id
* @param $type 		类型
* @param $number 	信息
* @param $money 	钱数
* @param $oid 		订单id
* @param $num 		加分数
*/
// 处理用户操作订单信息
/*protected function ordersendmessage($uuid,$type,$number=0,$money=0,$oid=0,$num=0,$message2="",$attribute=0)
{
	$data = M('member m')
						->join('__WECHAT__ w ON m.uuid = w.uuid')
						->where("m.uuid = $uuid")
						->field('m.score,w.openid,w.openid2,w.token')
						->find();
	switch ($type) {
		case '1':
			if ($attribute == 2) {
				$typemessage = "改派成功通知";
				$message = "改派成功,您的订单已经被系统重新派发.\n提示:多次改派将导致无法接单,请谨慎.\n您的信用分-".$number.",目前信用分为".$data['score']."分.";
			}else{
				$typemessage = "取消成功通知";
				$message = "取消成功,您的订单已经被系统重新派发.\n提示:多次取消将导致无法接单,请谨慎.\n您的信用分-".$number.",目前信用分为".$data['score']."分.";
			}
			break;
		case '2':
			$typemessage = "交付提醒通知";
			$message = "Hurry Up!距离交付音频时间仅剩20分钟.\n提示:无法交付将导致系统暂停向您发单.\n【申请延时】您只能申请延期30分钟交付1次.";
			break;
		case '3':
			$typemessage = "验收完成通知";
			if ($money == 0) {
			$money = "累计时间已发放";
			}else{
			$money = $money."元已发放至您的钱包";
			}
			if ($num == 0 && $data['score']==100) {
				$score = "您的信用分已满,请继续保持良好的交付习惯！";
			}else{
				$score = "您的信用分+".$num.",目前信用分为".$data['score']."分.";
			}
			$message = "音频已验收,客户评价:".$number."星,请再接再厉.\n提示:验收成功后,".$money.".\n".$score;
			if ($message2) {
				$message2 = "客户评价：".$message2;
			}
			break;
		case '4':
			$typemessage = "验收失败通知";
			$message = "您的音频未通过验收,理由:".$number.".\n提示:客户给予60分钟重新交付,请及时处理.\n建议您登录电脑端重新上传或申请【客服介入】";
			break;
	}
	 return $this->getorderMessage($data,$message,$typemessage,$message2,$oid,$attribute);
}
protected function getorderMessage($user,$message,$type,$message2='',$oid=0,$attribute=0){
	// $AccessToken = empty(RedisGet('Accesstoken')) ? $this->GetAccessToken(): RedisGet('Accesstoken');
	if ($attribute == 2 && $user['openid2']) {
		$AccessToken = $this->GetSingAccessToken();
		$data['template_id'] = C("TEMPLATESIGNMESSAGE");
		$data['touser'] = $user['openid2'];
	}else{
		$AccessToken = $this->GetAccessToken();
		$data['template_id'] = C("TEMPLATEMESSAGE");
		$data['touser'] = $user['openid'];
	}
	$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$AccessToken;
	$time = date('Y/m/d H:i:s',time());
	if ($oid != 0) {
		// $token = M('wechat')->where(array("openid"=>$user['openid']))->field('token')->find()['token'];
		$token = $user['token'];
		$data['url'] = "http://".C("ZB_URL").'.heardtech.com/credit.html?token='.$token.'&oid='.($oid);
	}
	$data['data']['first']['value'] = $message;
	$data['data']['first']['color'] = '#000000';
	$data['data']['keyword1']['value'] = $type;
	$data['data']['keyword1']['color'] = '#000000';
	$data['data']['keyword2']['value'] = $time."(信息下达)";
	$data['data']['keyword2']['color'] = '#000000';
	$data['data']['remark']['value'] = $message2;
	$data['data']['remark']['color'] = '#000000';
	$curl = curl_init($url);
	$header = array();
	$header[] = 'Content-Type: application/x-www-form-urlencoded';
	curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
	curl_setopt($curl, CURLOPT_HEADER, 0);
	curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($data));
	$response = curl_exec($curl);
	curl_close($curl);
	return json_decode($response);
}*/


// 获取微信AccessToken
public function GetAccessToken()
{
	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C("AppID").'&secret='.C("AppSecret");
	$data = json_decode(do_curl($url),TRUE);
	// RedisSet('Accesstoken',$data['access_token'],300);
	return $data['access_token'];
}
public function GetSingAccessToken()
{
	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C("SignAppID").'&secret='.C("SignAppSecret");
	$data = json_decode(do_curl($url),TRUE);
	// RedisSet('Accesstoken',$data['access_token'],300);
	return $data['access_token'];
}

// 发送websocket
public function postsocket($oid){
	$url = "http://".C("ZB_URL").".heardtech.com/Post/Socket";
	$arr['oid'] = $oid;
	$result = do_curl($url,$arr);
}
/*------------------------------------------------------------------------------------------*/

//阿里大于
	public function sendAlidayu($tel,$Code,$smsFreesignName='听说Heard')
	{
		$alidayu = new SendSMS();
		$result = $alidayu->send($recNum=$tel,$smsParam='',$smsTemplateCode=$Code,$smsFreesignName);
		return $result;
		// p($result);
	}
//阿里大于
	public function outtimeAlidayu($tel,$Code,$num,$time,$tel1,$tel2)
	{
		$alidayu = new SendSMS();
		$result = $alidayu->send($recNum=$tel,$smsParam='{"num":"'.$num.'","time":"'.$time.'","tel1":"'.$tel1.'","tel2":"'.$tel2.'"}',$smsTemplateCode=$Code,$smsFreesignName='听说Heard');
		return $result;
		// p($result);
	}
//阿里大于
	public function nobabyAlidayu($tel,$Code,$time,$phone)
	{
		$alidayu = new SendSMS();
		$result = $alidayu->send($recNum=$tel,$smsParam='{"time":"'.$time.'","tel":"'.$phone.'"}',$smsTemplateCode=$Code,$smsFreesignName='听说Heard');
		return $result;
	}
//阿里大于
	public function signreorderAlidayu($tel,$Code,$title,$uuid)
	{
		$alidayu = new SendSMS();
		$result = $alidayu->send($recNum=$tel,$smsParam='{"title":"'.$title.'","uuid":"'.$uuid.'"}',$smsTemplateCode=$Code,$smsFreesignName='听说Heard');
		return $result;
	}

function removecss($content){
	$content = preg_replace("/<a[^>]*>/i", "", $content);
	$content = preg_replace("/<\/a>/i", "", $content);
	$content = preg_replace("/<strong[^>]*>/i", "", $content);
	$content = preg_replace("/<\/strong>/i", "", $content);
	$content = preg_replace("/<section[^>]*>/i", "", $content);
	$content = preg_replace("/<\/section>/i", "", $content);
	$content = preg_replace("/<p[^>]*>/i", "", $content);
	$content = preg_replace("/<\/p>/i", "", $content);
	$content = preg_replace("/<span[^>]*>/i", "", $content);
	$content = preg_replace("/<\/span>/i", "", $content);
	$content = preg_replace("/<blockquote[^>]*>/i", "", $content);
	$content = preg_replace("/<\/blockquote>/i", "", $content);
	// $content = preg_replace("/<!--[^>]*-->/i", "", $content);//注释内容
	$content = preg_replace("/style=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/class=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/id=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/lang=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/width=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/height=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/border=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/face=.+?['|\"]/i",'',$content);//去除样式
	$content = preg_replace("/face=.+?['|\"]/",'',$content);//去除样式 只允许小写 正则匹配没有
	$content = preg_replace("/<img[^>]*>/i","",$content);
	// $content = preg_replace("/[\r\n+|\s+| +]/","", $content);
	// $content = str_replace('&lt;p&gt;','',$content);
	// $content = str_replace('&lt;/p&gt;','',$content);
	// $content = str_replace('\r\n','',$content);
	$content = preg_replace("/\n/",'',$content);
	$content = preg_replace("/\r/",'',$content);
	$content = preg_replace("/\t/",'',$content);
	$content = str_replace('&nbsp;','',$content);
	$content = str_replace('&lt;p&gt;&lt;br/&gt;&lt;/p&gt;','&lt;p&gt;&amp;nbsp;&lt;/p&gt;',$content);
	// echo htmlspecialchars($content);exit();
	return $content;
}
function fnGetCpmisWords($content){
	$content = str_replace('&nbsp;','',$content);
	$content = preg_replace("#　#","", $content);
	$content = preg_replace("# #","", $content);
	$content = preg_replace("/[\r\n]/","", $content);
	$content = preg_replace("/[\s]/","", $content);
	// echo strip_tags($content);exit();
	$content = (strip_tags($content));
	$content = str_replace('&lt;','<',$content);
	$content = str_replace('&gt;','>',$content);
	// echo $content;
	$sLen = mb_strlen($content, 'UTF-8')+0;
	// echo $sLen;exit();
	return $sLen;
}
function UpdateSendGetOrder($uuid){
	$num = M('order')->where("user_id=$uuid and type=1 and (status=3 or status=9)")->count();
	if ($num == 0) {
		M('sendmember')->where(array('uuid'=>$uuid))->save(array("getorder"=>0));
	}
}

	// 对参数进行处理
	protected function Parameterexplode($arr)
	{
		$arr = explode(",", $arr);
		foreach($arr as $key=>&$vo){
			$vo = substr(substr($vo, 1), 0 ,-1);
		}
		return $arr;
	}
	// 对参数进行处理
	protected function Parameterimplode($arr)
	{
		foreach($arr as $key=>&$vo){
			$vo = "-".$vo."-";
		}
		$arr = implode(",", $arr);
		return $arr;
	}
function add_verify_log($uuid,$message="",$status,$oid=0){
	$type = $oid==0?1:2;
	$relate_id = $oid==0?$status:$oid;
	M("verify_log")->add(array("uuid"=>$uuid,"type"=>$type,"relate_id"=>$relate_id,"note"=>$message,"date"=>time()));
}

function noticeemail($title,$content,$state=0,$oid=999999999){
	M('noticeemail')->add(array("title"=>$title,"content"=>$content,"oid"=>$oid,"type"=>$state));
}
	function pipeline($variable){
		$Redis = RedisNew();
		$Redis->pipeline();
		foreach ($variable as $key => $value) {
			$Redis->set('uuid'.$key,json_encode($value));
		}
		$Redis->exec();
		$Redis->close();
	}
}